import MD5 from "md5";
import axios from "axios";

const server = axios.create({
  withCredentials: true,
  timeout: 3000,
});

server.interceptors.request.use(
  (config) => {
    var userInfo = localStorage.getItem("userInfo");
    // 向请求头中塞入 token
    config.headers["x-token"] = userInfo ? JSON.parse(userInfo).token : "";
    var data = {};
    config.headers["x-platform"] = "pc";
    config.headers["x-mall-code"] = "SD001";
    data.timestamp = new Date().getTime();
    var str = "";
    var arr = config.arr || []; //["mobile","verificationCode","deviceToken","appType"]; //参数名称
    arr.forEach(function (key) {
      str += config.data[key];
    });
    str += data.timestamp;
    str += "md5Key";
    data.sign = MD5(str);
    // if (config.method.toUpperCase() == "POST") {
    //   config.data = Object.assign(config.data, data);
    // }
    if(!config.data) {
      config.data = data
    }
    if (config.method.toUpperCase() === "POST") {
      config.data = {
        ...config.data,  // 保留原有数据
        ...data,         // 合并新的 timestamp 和 sign
      };
    };
    console.log(config.data);

    return config;
  },
  (err) => Promise.reject(err)
);

server.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (err) => Promise.reject(err)
);

export default server;
